<?php
/**
 * Created by PhpStorm.
 * User: wyq
 * Date: 2021/8/3
 * Time: 16:00
 */


class Api extends Base_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admins_model');
        $this->load->model('users_model');
        $this->load->helper('common_helper');
        $this->load->model('Users_model');
        $this->load->service('Activity_service');
        $this->load->service('Jwt_service');
    }

    /*
     * 获取全部数据 get请求
     */
    public function index()
    {
        $data = $this->admins_model->findAll();
        foreach ($data as $k => &$v) {
            if ($v['status'] == 1) {
                $v['status'] = true;
            } else {
                $v['status'] = false;
            }
            if ($v['shows'] == 1) {
                $v['shows'] = true;
            } else {
                $v['shows'] = false;
            }
        }
        success($data);
    }

    /*
     * 获取单个数据 get请求
     */
    public function view($id)
    {
        $data = $this->admins_model->findOne($id);
        success($data);
    }

    /*
     * 新增一条数据
     */
    public function add()
    {
        $data = [
            'role_id' => 1,
            'nickname' => 'zw',
            'username' => date('Y-m-d H:i:s',time()),
            'password' => encrypt('123456')
            ];
        $data = $this->admins_model->add($data);
        if ($data) {
            success($data);
        } else {
            fail($data);
        }
    }

    /*
     * 修改一条数据
     */
    public function edit($id)
    {
        $post = file_get_contents('php://input');
        $data = json_decode($post, true);
        if ($data) {
            //修改页面逻辑
            $data['id'] = $id;
            $res = $this->admins_model->dell($data);
            if ($res) {
                success($res);
            } else {
                fail($res);
            }
        } else {
            //修改页面展示PUT请求
            $data = $this->admins_model->findOne($id);
            success($data);
        }
    }

    /*
     * 删除一条数据
     */
    public function delete($id)
    {
        $res = $this->admins_model->del($id);
        success($res);
    }

    public function upload()
    {
        $res = imgUpload();
        if (!$res) {
            fail(400,'上传失败!');
        }
        success($res,'上传成功!');
    }

    public function del_file()
    {
        $path = $_POST['img'];
        //注意相对路径和绝对路径问题，此为demo，开发请灵活判断
        //检测图片路径
        $path = substr($path, 14);
        if (file_exists($path)) {
            if (unlink($path)) {
                $id = $_POST['id'] + 1;
                die('删除成功,你删除了第' . $id . '张图片');
            } else {
                die("error");
            }
        } else {
            die("error");
        }
    }

    public function redis()
    {
        require_class('RedisCurd');
        $conn = RedisCurd::getInstance();
        $conn->selectDb(0);
        $conn->set('name',123);
    }

    public function send()
    {
        $email = getEmail();
        $email->sendmail('1835660809@qq.com','定时任务',date('Y-m-d H:i:s',time()));
    }

    public function test_model()
    {
        $data = $this->input->post();
        $value = [
            'prop_name' => '直升令牌',
            'desc' => '用了立马直升一级，哇！',
        ];
        $this->admins_model->commonInsert($data['table'], $value);
    }

    public function test()
    {
//        $phs = getBeanstalk();
//        $sql = 'INSERT INTO `wyq`.`jobtest`(`init_time`, `last_time`) VALUES (? , ?);';
//        $data = [time(), date("Y-m-d H:i:s")];
//        $phs->execSqlAsync($sql,$data);

        //给所有用户增加用户头像
        $res = $this->users_model->image();
        if ($res){
            success('',"操作{$res}条记录成功!");
        }
    }

    public function addDoc()
    {
        $query = getEs();
        $es = $query->getEs();
        // 写文档
//        $params = [
//            'index' => 'article',
//            'type' => '_doc',
//            'id' => 1,
//            'body' => [
//                'title' => "标题1",
//                'desn' => "12 月 8 日，历史上的今天，计算机的发明者成立 Eckert-Mauchly 计算机公司；D 语言发布；IBM 将计算部门出售给联想集团；人人网成立；第一个电脑文字处理器的发明者 Evelyn Berezin 逝世。",
//            ],
//        ];

        $params = [
            //索引
            'index' => 'artlce',
            //类型 es6之后一个索引对应一个type
            'type' => '_doc',
            //文档id
            'id' => 1,
            //字段值
            'body' => [
                'anchor' => 'wyq',
                'title' => '这是一篇文章',
                'desn' => '这是一篇文章的简介',
            ],
        ];

        $response = $es->index($params);
        success($response);
    }

    public function createDoc()
    {
        $query = getEs();
        $es = $query->getEs();
        $params = [
            //索引名
            'index' => 'article',
            'body' => [
                'settings' => [
                    //分区
                    'number_of_shards' => 5,
                    //分片
                    'number_of_replicas' => 1
                ],
                'mappings' => [
                    '_doc' => [
                        '_source' => [
                            'enabled' => true
                        ],
                        'properties' => [
                            'title' => [
                                //keyword 相当于数据查询的等于,不会进行分词操作
                                'type' => 'keyword'
                            ],
                            'desn' => [
                                'type' => 'text',
                                //ik分词器操作:ik_max_word
                                'analyzer' => 'ik_max_word',
                                'search_analyzer' => 'ik_max_word'
                            ]
                        ]
                    ]
                ]
            ]
        ];
        $data = $es->indices()->create($params);
        success($data);
    }

    public function delIndex()
    {
        $client = getEs();
        $res = $client->delIndex("articles");
        if ($res['code'] != 200) {
            fail(400, $res['message']);
        }
        success($res);
    }

    public function updateDoc()
    {
        $query = getEs();
        $client = $query->getEs();
        //修改指定索引指定文档的内容
        $params3 = [
            //索引
            'index' => 'artlce',
            //类型 es6之后一个索引对应一个type
            'type' => '_doc',
            //文档id
            'id' => 1,
            //字段值
            'body' => [
                'doc' =>[
                    'anchor' => 'wyq123',
                ]
            ],
        ];
        $response = $client->update($params3);
    }

    public function createIndex()
    {
        $es = getEs();
        $data = [
            //文档的字段以及字段的类型
            'uses_id' => [
                'type' => 'integer'
            ],
            'nickname' => [
                //keyword类型的字段只能通过精确值搜索到
                'type'=> 'keyword'
            ],
            'pageViews' => [
                'type' => 'integer'
            ],
            'likes' => [
                'type' => 'integer'
            ],
            'title' => [
                'type' => 'text',
                //ik分词器的ik_max_word模式
                'analyzer' => 'ik_max_word',
                'search_analyzer' => 'ik_max_word'
            ],
            'content' => [
                'type' => 'text',
                //ik分词器的ik_max_word模式
                'analyzer' => 'ik_max_word',
                'search_analyzer' => 'ik_max_word'
            ],
            'create_time' => [
                'type' => 'integer'
            ],
            'update_time' => [
                'type' => 'date',
                //date的格式
                "format" => "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
            ],
        ];
       $res = $es->createIndex('articles',5,1,$data);
        if ($res) {
            success($res);
        }
        fail($res);
    }

    public function swoole()
    {
        Swoole\Event::defer(function () {
            echo "hello\n";
        });
    }

    public function address()
    {
        $data = $this->input->post();
        $address = $data['address'] ?:"";
        $location = $data['location'] ?:"";
        $gDMapKey = config_item('gDMapKey');
        $addressToLocationUrl = config_item('addressToLocation');
        $locationToAddressUrl = config_item('LocationToAddress');
//        $url = $addressToLocationUrl ."?address={$address}&output=json&key=".$gDMapKey;
        $url = $locationToAddressUrl."?location={$location}&output=json&key=".$gDMapKey;
        $res = curl_request($url,false);
        $res = json_decode($res,true);
        success($res);
    }

    public function logsCount()
    {
//        SeasLog::setLogger('userLogin');
        $all = Logs::countLog(SEASLOG_DEBUG,'userLogin');
        $waring = Logs::detailLog(SEASLOG_DEBUG,'',date('Ymd',time()));
        var_dump($all);
        echo "<hr>";
        var_dump($waring);
    }
}